package cn.com.dycc.topic_activity.service;

import java.io.UnsupportedEncodingException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cn.com.dycc.common.attach.dao.AttachDao;
import cn.com.dycc.common.attach.entity.Attach;
import cn.com.dycc.common.entity.DeleteEntity;
import cn.com.dycc.common.log.Constants;
import cn.com.dycc.common.log.SystemServiceLog;
import cn.com.dycc.infomation_center.service.Pb_Party_InformationNotFoundException;
import cn.com.dycc.party_org.organize.dao.OrganizeDao;
import cn.com.dycc.party_org.organize.entity.OrganizeEntity;
import cn.com.dycc.party_org.organize.param.PartyInfoParam;
import cn.com.dycc.party_org.organize.service.OrganizeService;
import cn.com.dycc.study_manage.integral.dao.Pb_Integral_Dept_LogDao;
import cn.com.dycc.study_manage.integral.dao.Pb_Integral_RuleDao;
import cn.com.dycc.study_manage.integral.entity.Pb_Integral_Dept_Log;
import cn.com.dycc.study_manage.integral.entity.Pb_Integral_Rule;
import cn.com.dycc.study_manage.integral.param.Pb_Integral_RuleParam;
import cn.com.dycc.sys_manage.deptsysmanagement.dao.DeptDao;
import cn.com.dycc.topic_activity.dao.Pb_Activity_DeptDao;
import cn.com.dycc.topic_activity.dao.Pb_Activity_EnterDao;
import cn.com.dycc.topic_activity.dao.Pb_Activity_VoteDao;
import cn.com.dycc.topic_activity.dao.Pb_Special_ActivityDao;
import cn.com.dycc.topic_activity.entity.Pb_Activity_Dept;
import cn.com.dycc.topic_activity.entity.Pb_Special_Activity;
import cn.com.dycc.topic_activity.entity.Special_Activity_Count;
import cn.com.dycc.topic_activity.param.Pb_Special_ActivityParam;
import cn.com.dycc.util.AttachUtil;
import cn.com.dycc.util.ConfigRegex;
import cn.com.dycc.util.DateUtil;
import cn.com.dycc.util.FileUtil;
import cn.com.dycc.util.JsonObjectResult;
import cn.com.dycc.util.PageObjectUtil;
import cn.com.dycc.util.StringUtil;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;

@Service("pb_Special_ActivityService")
@Transactional
public class Pb_Special_ActivityServiceImpl implements Pb_Special_ActivityService{

	@Resource
	private Pb_Special_ActivityDao pb_Special_ActivityDao;
	
	@Resource
	private AttachDao attachDao;
	
	@Resource
	private Pb_Integral_Dept_LogDao pb_Integral_Dept_LogDao;
	
	@Resource
	private Pb_Integral_RuleDao pb_Integral_RuleDao;
	
	@Resource
	private Pb_Activity_DeptDao pb_Activity_DeptDao;
	
	@Resource
	private Pb_Activity_VoteDao pb_Activity_VoteDao;
	
	@Resource
	private Pb_Activity_EnterDao pb_Activity_EnterDao;
	
	@Resource
	private DeptDao deptDao;
	
	@Resource
	private OrganizeDao organizeDao;
	
	@Resource
	private OrganizeService organizeService;
	
	
	
	@SystemServiceLog(description=Constants.SPECIAL_ACTIVITY_ADD)
	public int addPb_Special_Activity(Pb_Special_ActivityParam param, HttpServletRequest request)
			throws Pb_Special_ActivityNotFoundException {
		checkParam(param);
		HttpSession session=request.getSession();
		String opt_user_id=(String)session.getAttribute("id");
		String create_date=DateUtil.getNowTimestamp().toString();
		String org_id=(String)session.getAttribute("org_id");
		String dept_id_send=(String)session.getAttribute("dept_id");
		StringBuilder builder=new StringBuilder();
		if(param.getActivity_name()==null||param.getActivity_name().trim().isEmpty()){
			builder.append("活动名称不能为空;");
		}
		if(param.getDate_b()==null||param.getDate_b().trim().isEmpty()){
			builder.append("活动开始时间不能为空;");
		}
		if(param.getDate_e()==null||param.getDate_e().trim().isEmpty()){
			builder.append("活动结束时间不能为空;");
		}
		if(param.getEnter_date_b()==null||param.getEnter_date_b().trim().isEmpty()){
			builder.append("报名开始时间不能为空;");
		}
		if(param.getEnter_date_e()==null||param.getEnter_date_e().trim().isEmpty()){
			builder.append("报名结束时间不能为空;");
		}
		if(!"".equals(builder.toString())){
			throw new Pb_Special_ActivityNotFoundException(builder.toString());
		}
		param.setOpt_user_id(opt_user_id);
		param.setCreate_date(create_date);
		param.setState("Y");
		param.setOrg_id(org_id);
		param.setDept_id_send(dept_id_send);
		param.setIssue_flag("0");
		List<Pb_Special_Activity> lists = getServiceList(param);
		Pb_Special_Activity entity=lists.get(0);
		int d = pb_Special_ActivityDao.savePb_Special_Activity(entity);
		if(d>0){
			if(param.getAttachs()!=null&&!param.getAttachs().trim().isEmpty()){
				saveT_Attach(param.getAttachs(),entity,AttachUtil.special_activity_attach_type);
			}
			
			if(param.getThumbnails()!=null&&!param.getThumbnails().trim().isEmpty()){
				saveT_Attach(param.getThumbnails(),entity,AttachUtil.special_activity_lst_attach_type);
			}
			//20180725 start
			List<Pb_Activity_Dept> activity_dept_list=new ArrayList<Pb_Activity_Dept>();
			Pb_Activity_Dept activity_dept=new Pb_Activity_Dept();
			activity_dept.setActivity_id(entity.getActivity_id());
			activity_dept.setDept_id(entity.getDept_id_send());
			activity_dept.setState(entity.getState());
			activity_dept.setOrg_id(entity.getOrg_id());
			activity_dept.setCreate_date(entity.getCreate_date());
			activity_dept.setOpt_user_id(entity.getOpt_user_id());
			activity_dept_list.add(activity_dept);
			
			pb_Activity_DeptDao.addPb_Activity_Dept(activity_dept_list);
			//20180725 end
			
			
		}
		
		return d;
		
	}

	

	

	public JsonObjectResult findPb_Special_ActivityByParam(Pb_Special_ActivityParam param,
			HttpServletRequest request) throws Pb_Special_ActivityNotFoundException {
		List<Pb_Special_Activity> lists = new ArrayList<Pb_Special_Activity>();
		
		checkParam(param);
		HttpSession session=request.getSession();
		String user_id=(String)session.getAttribute("id");
		String dept_no=(String)session.getAttribute("dept_no");
		String org_id=(String)session.getAttribute("org_id");
		param.setOrg_id(org_id);
		List<String> dept_party_list=new ArrayList<String>();
		if(param.getOpt_user_id()==null&&"1".equals(param.getLeader_flag())){
			List<String> childDeptIds=deptDao.findDeptBylowPid(dept_no);
			System.out.println("dept_no:"+dept_no);
			System.out.println("childDeptIds:"+childDeptIds);
			for(String str:childDeptIds){
				List<OrganizeEntity> organizeEntities=organizeDao.findOrganizeByOwnDeptId(str);
				for(OrganizeEntity entity:organizeEntities){
					dept_party_list.add(entity.getDept_id());
				}
			}
			if(!dept_party_list.isEmpty()){
				param.setDept_party_list(dept_party_list);
			}else {
				throw new Pb_Special_ActivityNotFoundException("该部门及其子部门下无相应的党支部信息");
			}
			System.out.println("dept_party_list:"+dept_party_list);
		}
		
		param = realParam(param, request);
		System.out.println("param:"+param);
		String count = pb_Special_ActivityDao.getPb_Special_ActivityCountByParam(param);
		System.out.println("count:"+count);
		if ("0".equals(count)) {
			
			return new JsonObjectResult(lists);
		}
		param = (Pb_Special_ActivityParam) PageObjectUtil.getSqlPageObject(count, param);
		lists = pb_Special_ActivityDao.findPb_Special_ActivityByParam(param);
		//20180730 start		
		Map<String, Object> today_map=new HashMap<String, Object>();
		Map<String, Object> enter_map=new HashMap<String, Object>();
		if(param.getOpt_user_id()!=null&&!param.getOpt_user_id().trim().isEmpty()){
			today_map.put("vote_user_id", user_id);
			enter_map.put("user_id", user_id);
		}
		List<String> activitys=new ArrayList<String>();
		for(Pb_Special_Activity activity:lists){
			activitys.add(activity.getActivity_id());
		}
		today_map.put("activity_list", activitys);
		enter_map.put("activity_list", activitys);
		String now_date=DateUtil.getNowDate(DateUtil.DATE_FMT);
		today_map.put("vote_date", now_date);
		today_map.put("vote_date_e",now_date);
		
		List<Map<String, String>> vote_group_count_today=pb_Activity_VoteDao.getPb_Activity_VoteGroupCountByParam(today_map);
		List<Map<String, String>> enter_group_count=pb_Activity_EnterDao.getPb_Activity_EnterGroupCountByParam(enter_map);
		for(Map<String, String> map_today:vote_group_count_today){
			String count_today=map_today.get("count");
			String activity_id=map_today.get("activity_id");
			if(!"0".equals(count_today)){
				for(int i=0;i<lists.size();i++){
					Pb_Special_Activity pb_Special_Activity=lists.get(i);
					if(activity_id.equals(pb_Special_Activity.getActivity_id())){
						pb_Special_Activity.setVote_flag("1");
						lists.set(i, pb_Special_Activity);
						break;
					}
				}
			}		
		}
		for(Map<String, String> map_enter:enter_group_count){
			String count_old=map_enter.get("count");
			String activity_id=map_enter.get("activity_id");
			if(!"0".equals(count_old)){
				for(int i=0;i<lists.size();i++){
					Pb_Special_Activity pb_Special_Activity=lists.get(i);
					if(activity_id.equals(pb_Special_Activity.getActivity_id())){
						pb_Special_Activity.setEnter_flag("1");
						lists.set(i, pb_Special_Activity);
						break;
					}
				}
			}		
		}
		
		//20180730 end
		return new JsonObjectResult(count,lists);
	}
	
	/**
	 * 实际参数
	 * 
	 * @param param
	 * @param request
	 * @return
	 */
	public Pb_Special_ActivityParam realParam(Pb_Special_ActivityParam param, HttpServletRequest request) {
		if(param.getActivity_name()!=null&&!param.getActivity_name().trim().isEmpty()){
			param.setActivity_name(StringUtil.format_mh_str(param.getActivity_name()));
		}
		if(param.getActivity_des()!=null&&!param.getActivity_des().trim().isEmpty()){
			param.setActivity_des(StringUtil.format_mh_str(param.getActivity_des()));
		}
		if(param.getOrder()==null||param.getOrder().isEmpty()||"1".equals(param.getOrder())){
			param.setOrder("p.create_date desc");
		}else if("2".equals(param.getOrder())){
			param.setOrder("p.create_date asc");
			
		}else{
			param.setOrder(null);//手动防止SQL注入
		}
		return param;
	}
	
	/**
	 * 校验 @param param @return @throws
	 */
	public void checkParam(Pb_Special_ActivityParam param) {
		if (param == null) {
			throw new Pb_Special_ActivityNotFoundException("未登录或超时,请重新登录");
		}
		StringBuilder builder=new StringBuilder();
		if(param.getDate_b()!=null&&!param.getDate_b().trim().isEmpty()){
			if(!param.getDate_b().matches(ConfigRegex.DATEREGEX)){
				builder.append("活动开始时间格式不对,应为yyyy-MM-dd;");
			}
		}
		if(param.getDate_e()!=null&&!param.getDate_e().trim().isEmpty()){
			if(!param.getDate_e().matches(ConfigRegex.DATEREGEX)){
				builder.append("活动结束时间格式不对,应为yyyy-MM-dd;");
			}
		}
		if(param.getEnter_date_b()!=null&&!param.getEnter_date_b().trim().isEmpty()){
			if(!param.getEnter_date_b().matches(ConfigRegex.DATEREGEX)){
				builder.append("报名开始时间格式不对,应为yyyy-MM-dd;");
			}
		}
		if(param.getEnter_date_e()!=null&&!param.getEnter_date_e().trim().isEmpty()){
			if(!param.getEnter_date_e().matches(ConfigRegex.DATEREGEX)){
				builder.append("报名结束时间格式不对,应为yyyy-MM-dd;");
			}
		}
		if(!"".equals(builder.toString())){
			throw new Pb_Special_ActivityNotFoundException(builder.toString());
		}
		

	}

	public List<Pb_Special_Activity> getServiceList(Pb_Special_ActivityParam param) {
		Pb_Special_Activity entity = new Pb_Special_Activity();

		if(param.getActivity_id()!=null&&!param.getActivity_id().trim().isEmpty()){
			entity.setActivity_id(param.getActivity_id());
		}	
		entity.setActivity_name(param.getActivity_name());
		entity.setDate_b(DateUtil.getSqlTypeDate(param.getDate_b()));
		entity.setDate_e(DateUtil.getSqlTypeDate(param.getDate_e()));
		entity.setEnter_date_b(DateUtil.getSqlTypeDate(param.getEnter_date_b()));
		entity.setEnter_date_e(DateUtil.getSqlTypeDate(param.getEnter_date_e()));
		if(param.getActivity_des()!=null&&!param.getActivity_des().trim().isEmpty()){
			try {
				entity.setActivity_des(StringUtil.decode(param.getActivity_des()));
			} catch (UnsupportedEncodingException e) {
				throw new Pb_Special_ActivityNotFoundException("对活动内容解码失败");
			}
		}
		
		entity.setDept_id_send(param.getDept_id_send());
		entity.setOrder_id(param.getOrder_id());
		entity.setState(param.getState());
		entity.setOrg_id(param.getOrg_id());
		if(param.getCreate_date()!=null&&!param.getCreate_date().trim().isEmpty()){
			entity.setCreate_date(Timestamp.valueOf(param.getCreate_date()));
		}
		entity.setOpt_user_id(param.getOpt_user_id());
		entity.setIssue_flag(param.getIssue_flag());
		
		List<Pb_Special_Activity> lists = new ArrayList<Pb_Special_Activity>();
		lists.add(entity);
		return lists;
	}
	
	/**
	 * 将临时目录下的文件移到正式目录
	 */
	private void saveT_Attach(String attachInfos,Pb_Special_Activity entity,String attach_type){
		List<Attach> listAttach=new ArrayList<Attach>();
		
		if(attachInfos!=null&&!attachInfos.trim().isEmpty()){
			
			String str=attachInfos.trim();
			
			JSONArray json=JSONArray.fromObject(str);
			
			for(int i=0;i<json.size();i++){
				
				Object check=json.get(i);
				
				
				if("null".equals(check.toString())){
					continue;
				}
				JSONObject job = json.getJSONObject(i); // 遍历 jsonarray 数组，把每一个对象转成 json 对象			
				String attach_ext=(String)job.get("attach_ext");
				String attach_path=(String)job.get("attach_path");
				String attach_size=(String)job.get("attach_size");
				String title=(String)job.get("title");
				
				Attach attach=new Attach();
				attach.setMessage_no(entity.getActivity_id());
				attach.setAttach_type(Integer.valueOf(attach_type));
				attach.setTitle(title);
				attach.setAttach_ext(attach_ext);
				attach.setAttach_path(attach_path);
				attach.setAttach_size(attach_size);				
				attach.setOrg_id(entity.getOrg_id());
				attach.setOpt_user_id(entity.getOpt_user_id());
				
				attach.setCreate_date(DateUtil.getNowTimestamp());
				
				listAttach.add(attach);			
			}
		}
		
		List<Attach> newListAttach=FileUtil.moveFile(listAttach,"infomation_center");
		
		if(newListAttach!=null){
			for(Attach attach:newListAttach){
				
				attachDao.insertAttach(attach);
			}
						
		}
		
	}





	@SystemServiceLog(description=Constants.PB_SPECIAL_ACTIVITY_UPDATE)
	public int updatePb_Special_Activity(Pb_Special_ActivityParam param, HttpServletRequest request)
			throws Pb_Special_ActivityNotFoundException {
		HttpSession session=request.getSession();
		String org_id=(String)session.getAttribute("org_id");
		String opt_user_id=(String)session.getAttribute("id");
		String dept_id_send=(String)session.getAttribute("dept_id");
		checkParam(param);
		if (param.getActivity_id() == null || param.getActivity_id().trim().isEmpty()) {
			throw new Pb_Special_ActivityNotFoundException("请选择专题活动");
		}
		Pb_Special_ActivityParam param2=new Pb_Special_ActivityParam();
		param2.setActivity_id(param.getActivity_id());
		param2.setOrg_id(org_id);
		param2.setStart(0);
		param2.setEnd(1);
		//String count=pb_Special_ActivityDao.getPb_Special_ActivityCountByParam(param2);
		List<Pb_Special_Activity> activities=pb_Special_ActivityDao.findPb_Special_ActivityByParam(param2);
		
		if(activities.size()<=0){	
			throw new Pb_Special_ActivityNotFoundException("该专题活动不存在");
		}else{
			if("1".equals(activities.get(0).getIssue_flag())){
				throw new Pb_Special_ActivityNotFoundException("该专题活动已被发布,不能在发布或修改");
			}
		}
		
		//return 1;
		
		System.out.println("党组织部门:"+dept_id_send);
		if(dept_id_send==null||dept_id_send.trim().isEmpty()){
			throw new Pb_Special_ActivityNotFoundException("该用户不是党员,不能在发布或修改");
		}
		List<Pb_Special_Activity> lists = getServiceList(param);
		int d = pb_Special_ActivityDao.updatePb_Special_Activity(lists);
		if(d>0){
			Pb_Special_Activity entity=new Pb_Special_Activity();
			entity.setActivity_id(lists.get(0).getActivity_id());
			entity.setOrg_id(org_id);
			entity.setOpt_user_id(opt_user_id);
			entity.setDept_id_send(dept_id_send);
			if(param.getAttachs()!=null&&!param.getAttachs().trim().isEmpty()){
				saveT_Attach(param.getAttachs(),entity,AttachUtil.special_activity_attach_type);
			}
			
			if(param.getThumbnails()!=null&&!param.getThumbnails().trim().isEmpty()){
				List<Attach> attachList=attachDao.findAttachByMesNoAndType(param.getActivity_id(),Integer.valueOf(AttachUtil.special_activity_lst_attach_type),org_id);
				if(attachList.size()>0){
					Attach attach=attachList.get(0);
					AttachUtil.removeFile(attach.getAttach_path());
					attachDao.deleteAttach(attach);
				}
				saveT_Attach(param.getThumbnails(),entity,AttachUtil.special_activity_lst_attach_type);
			}
			if(param.getIssue_flag()!=null&&"1".equals(param.getIssue_flag())){
				
				Pb_Integral_RuleParam param1=new Pb_Integral_RuleParam();
				param1.setStart(0);
				param1.setEnd(1);
				List<Pb_Integral_Rule> list2=pb_Integral_RuleDao.findPb_Integral_RuleByParam(param1);
				if(list2.size()>0){
					
					Pb_Integral_Rule rule=list2.get(0);
					Pb_Integral_Dept_Log entity1=new Pb_Integral_Dept_Log();
					entity1.setIntegral_val(rule.getActivity_send_val());
					entity1.setLog_flag("1");
					entity1.setLog_des("");
					entity1.setDept_id(entity.getDept_id_send());
					entity1.setState("Y");
					entity1.setOrg_id(entity.getOrg_id());
					entity1.setCreate_date(entity.getCreate_date());
					entity1.setOpt_user_id(entity.getOpt_user_id());
					entity1.setInfo_id(entity.getActivity_id());
					//20180802 start
					OrganizeEntity org=organizeDao.findOrganizeByDeptId(entity.getDept_id_send(),org_id);
					String dept_name=org.getDept_name();
					String log_des=dept_name+"于"+DateUtil.getNowDate(DateUtil.TIME_FMT)+"操作【"+activities.get(0).getActivity_name()+"】活动发帖,获取积分"+rule.getActivity_send_val()+"分";
					System.out.println("log_des:"+log_des);
					entity1.setLog_des(log_des);
					//entity1.setLog_des("自动书写信息");
					//20180802 end
					pb_Integral_Dept_LogDao.savePb_Integral_Dept_Log(entity1);
				}
			}
		}
		return d;
	}

	@SystemServiceLog(description=Constants.PB_SPECIAL_ACTIVITY_DELETE)
	public int deletePb_Special_Activity(String[] attrStrs, HttpServletRequest request)
			throws Pb_Special_ActivityNotFoundException {
		HttpSession session=request.getSession();
		String org_id=(String)session.getAttribute("org_id");
		if (attrStrs == null) {
			throw new Pb_Party_InformationNotFoundException("请选择要删除的专题活动发起信息");
		}
		StringBuilder builder=new StringBuilder();
		for(String activity_id:attrStrs){
			Pb_Special_ActivityParam param=new Pb_Special_ActivityParam();
			param.setActivity_id(activity_id);
			param.setOrg_id(org_id);
			param.setIssue_flag("1");
			String count=pb_Special_ActivityDao.getPb_Special_ActivityCountByParam(param);
			if(!"0".equals(count)){
				builder.append("专题活动:"+activity_id+"已发布，不能被删除;");
			}
		}
		if(!"".equals(builder.toString())){
			throw new Pb_Special_ActivityNotFoundException(builder.toString());
		}
		DeleteEntity deleteEntity=new DeleteEntity();
		deleteEntity.setInfo_ids(attrStrs);
		deleteEntity.setOrg_id(org_id);
		int d = pb_Special_ActivityDao.deletePb_Special_Activity(deleteEntity);
		return d;
	}





	public JsonObjectResult findSpecial_Activity_CountByParam(Pb_Special_ActivityParam param,
			HttpServletRequest request) throws Pb_Special_ActivityNotFoundException {
		
		List<Special_Activity_Count> lists = new ArrayList<Special_Activity_Count>();		
		checkParam(param);
		HttpSession session=request.getSession();
		
		String dept_id=(String)session.getAttribute("dept_id");
		String org_id=(String)session.getAttribute("org_id");
		param.setOrg_id(org_id);
		if(dept_id==null){
			throw new Pb_Special_ActivityNotFoundException("该用户不是党员");
		}
		//List<String> dept_party_list=new ArrayList<String>();
		if((param.getDept_id_send()==null||param.getDept_id_send().trim().isEmpty())&&(param.getOpt_user_id()==null||param.getOpt_user_id().trim().isEmpty())&&"1".equals(param.getLeader_flag())){
			PartyInfoParam partyInfoParam=new PartyInfoParam(); 
			String party_dept=dept_id;
			List<String> dept_party_list=organizeService.findTreeByPidLine(request, partyInfoParam, party_dept);
			
			if(!dept_party_list.isEmpty()){
				param.setDept_party_list(dept_party_list);
			}else {
				throw new Pb_Special_ActivityNotFoundException("登录用户党支部信息没有查找到");
			}
			System.out.println("dept_party_list:"+dept_party_list);
		}
		
		param = realParam(param, request);
		System.out.println("param:"+param);
		String count = pb_Special_ActivityDao.getPb_Special_ActivityCountByParam(param);
		
		if ("0".equals(count)) {
			
			return new JsonObjectResult(lists);
		}
		param = (Pb_Special_ActivityParam) PageObjectUtil.getSqlPageObject(count, param);
		lists = pb_Special_ActivityDao.findSpecial_Activity_CountByParam(param);
		
		return new JsonObjectResult(count,lists);
	}





	






}
